from PySide2.QtCore import Qt
from PySide2.QtWidgets import QListWidgetItem, QTableWidgetItem
from src.lib.myconf import myconf


class AppConfig():
    cf = myconf()

    def __init__(self, defaults=None):
        self.__init()

    def __init(self):
        self.cf.read("config.ini", "utf-8-sig")

    def __newListItem(self, text, toolTip):
        # 新建表项
        item = 0
        item = QListWidgetItem()
        item.setText(text)
        item.setToolTip(toolTip)
        return item

    def __readCfgDebugAT(self, ui):
        try:
            text = self.cf.get("debugAT", "at")
            if len(text) > 0:
                list_s = text.split('&')
                for i in range(0, ui.count()):
                    ui.takeItem(0)
                for i in range(0, len(list_s)):
                    try:
                        buff = list_s[i].split("|")
                        if (len(buff) == 3):
                            item = self.__newListItem(
                                buff[0], buff[1] + "\n\n" + buff[2])
                            ui.addItem(item)
                    except Exception:
                        pass
            else:
                raise
        except Exception:
            self.cf.add_section("debugAT")
            text = ""
            for i in range(0, ui.count()):
                item = ui.item(i)
                cmd, hint = item.toolTip().split('\n\n', 1)
                text += item.text() + "|" + cmd + "|" + hint + "&"
            self.cf.set("debugAT", "at", text)

    def __readCfgLoopAT(self, ui):
        try:
            text = self.cf.get("循环调试", "AT_CMD")
            i_row_count = ui.rowCount()
            for i in range(i_row_count):
                ui.removeRow(0)

            text_list = text.split("&")
            for text_s in text_list:
                row = ui.rowCount()
                if (len(text_s) <= 0):
                    break
                check, at, time, nul = text_s.split("|", 3)
                ui.insertRow(int(row))
                newItem = QTableWidgetItem(str(at))
                if (int(check) == 1):
                    newItem.setCheckState(Qt.Checked)
                else:
                    newItem.setCheckState(Qt.Unchecked)
                ui.setItem(row, 0, newItem)
                newItem = QTableWidgetItem(str(time))
                ui.setItem(row, 1, newItem)
        except Exception:
            self.cf.add_section("循环调试")
            i_row_count = ui.rowCount()
            text = ""
            for i in range(i_row_count):
                text = text + str(int(bool(ui.item(i, 0).checkState()))) + "|"
                text = text + ui.item(i, 0).text() + "|"
                text = text + ui.item(i, 1).text() + "|"
                text = text + "&"
            self.cf.set("循环调试", "AT_CMD", text)

    def __readCfgDfu(self, ui):
        try:
            ui.setText(self.cf.get("有线升级", "upFilePath"))
        except Exception:
            self.cf.add_section("有线升级")
            self.cf.set("有线升级", "upFilePath", ui.text())

    def __readCfgJLinkPath(self, ui):
        try:
            ui.setText(self.cf.get("工厂烧录", "JLinkPath"))
        except Exception:
            self.cf.add_section("工厂烧录")
            self.cf.set("工厂烧录", "JLinkPath", ui.text())

    def __readCfgJLinkBurnPath(self, ui):
        try:
            ui.setText(self.cf.get("工厂烧录", "JLinkBurnPath"))
        except Exception:
            #self.cf.add_section("工厂烧录")
            self.cf.set("工厂烧录", "JLinkBurnPath", ui.text())

    def __readCfgJLinkChipType(self, ui):
        try:
            text = self.cf.get("工厂烧录", "JLinkChipType")
            if text != "":
                current,data = text.split("|", 1)
                buff = []
                buff = data.split("&")
                if len(buff) > 0:
                    ui.clear()
                for i in range(0, len(buff)):
                    if buff[i] != "":
                        ui.addItem(buff[i])
                ui.setCurrentIndex(int(current))
        except Exception:
            self.__writeCfgJLinkChipType(ui)

    def __readCfgJLinkBurnAddr(self, ui):
        try:
            ui.setText(self.cf.get("工厂烧录", "JLinkBurnAddr"))
        except Exception:
            self.cf.set("工厂烧录", "JLinkBurnAddr", ui.text())

    def __readCfgSTLinkPath(self, ui):
        try:
            ui.setText(self.cf.get("工厂烧录", "STLinkPath"))
        except Exception:
            self.cf.set("工厂烧录", "STLinkPath", ui.text())

    def __readCfgSTLinkBurnPath(self, ui):
        try:
            ui.setText(self.cf.get("工厂烧录", "STLinkBurnPath"))
        except Exception:
            self.cf.set("工厂烧录", "STLinkBurnPath", ui.text())

    def __readCfgSTLinkChipType(self, ui):
        try:
            text = self.cf.get("工厂烧录", "STLinkChipType")
            if text != "":
                current,data = text.split("|", 1)
                buff = []
                buff = data.split("&")
                if len(buff) > 0:
                    ui.clear()
                for i in range(0, len(buff)):
                    if buff[i] != "":
                        ui.addItem(buff[i])
                ui.setCurrentIndex(int(current))
        except Exception:
            self.__writeCfgSTLinkChipType(ui)

    def __readCfgSTLinkBurnAddr(self, ui):
        try:
            ui.setText(self.cf.get("工厂烧录", "STLinkBurnAddr"))
        except Exception:
            self.cf.set("工厂烧录", "STLinkBurnAddr", ui.text())

    def readAllCfg(self, ui):
        self.__readCfgDebugAT(ui.lvw_debugAT)
        self.__readCfgLoopAT(ui.tbw_loopDebugAT)
        self.__readCfgDfu(ui.le_upFilePath)

        self.__readCfgJLinkPath(ui.le_jlinkFilePath)
        self.__readCfgJLinkBurnPath(ui.le_jlinkBurnFilePath)
        self.__readCfgJLinkChipType(ui.cmb_jlinkChipType)
        self.__readCfgJLinkBurnAddr(ui.le_jlinkBurnAddr)

        self.__readCfgSTLinkPath(ui.le_stlinkFilePath)
        self.__readCfgSTLinkBurnPath(ui.le_stlinkBurnFilePath)
        self.__readCfgSTLinkChipType(ui.cmb_stlinkChipType)
        self.__readCfgSTLinkBurnAddr(ui.le_stlinkBurnAddr)

        #节点全部展开
        ui.twd_lightType.expandAll()

    # def __writeCfgSerial(self, ui):
    #     self.cf.set("Serial", "baud_list_i", str(ui.currentIndex()))

    def __writeCfgDebugAT(self, ui):
        text = ""
        for i in range(0, ui.count()):
            item = ui.item(i)
            cmd, hint = item.toolTip().split('\n\n', 1)
            text += item.text() + "|" + cmd + "|" + hint + "&"
        self.cf.set("debugAT", "at", text)

    def __writeCfgLoopAT(self, ui):
        i_row_count = ui.rowCount()
        text = ""
        for i in range(i_row_count):
            text = text + str(int(bool(ui.item(i, 0).checkState()))) + "|"
            text = text + ui.item(i, 0).text() + "|"
            text = text + ui.item(i, 1).text() + "|"
            text = text + "&"
        self.cf.set("循环调试", "AT_CMD", text)

    def __writeCfgDfu(self, ui):
        self.cf.set("有线升级", "upFilePath", ui.text())

    def __writeCfgJLinkPath(self, ui):
        self.cf.set("工厂烧录", "JLinkPath", ui.text())

    def __writeCfgJLinkBurnPath(self, ui):
        self.cf.set("工厂烧录", "JLinkBurnPath", ui.text())

    def __writeCfgJLinkChipType(self, ui):
        text = ""
        text += str(ui.currentIndex()) + "|"
        for i in range(0, ui.count()):
            text += ui.itemText(i) + "&"
        self.cf.set("工厂烧录", "JLinkChipType", text)

    def __writeCfgJLinkBurnAddr(self, ui):
        self.cf.set("工厂烧录", "JLinkBurnAddr", ui.text())

    def __writeCfgSTLinkPath(self, ui):
        self.cf.set("工厂烧录", "STLinkPath", ui.text())

    def __writeCfgSTLinkBurnPath(self, ui):
        self.cf.set("工厂烧录", "STLinkBurnPath", ui.text())

    def __writeCfgSTLinkChipType(self, ui):
        text = ""
        text += str(ui.currentIndex()) + "|"
        for i in range(0, ui.count()):
            text += ui.itemText(i) + "&"
        self.cf.set("工厂烧录", "STLinkChipType", text)

    def __writeCfgSTLinkBurnAddr(self, ui):
        self.cf.set("工厂烧录", "STLinkBurnAddr", ui.text())

    def saveAllCfg(self, ui):
        self.__writeCfgDebugAT(ui.lvw_debugAT)
        self.__writeCfgLoopAT(ui.tbw_loopDebugAT)
        self.__writeCfgDfu(ui.le_upFilePath)

        self.__writeCfgJLinkPath(ui.le_jlinkFilePath)
        self.__writeCfgJLinkBurnPath(ui.le_jlinkBurnFilePath)
        self.__writeCfgJLinkChipType(ui.cmb_jlinkChipType)
        self.__writeCfgJLinkBurnAddr(ui.le_jlinkBurnAddr)

        self.__writeCfgSTLinkPath(ui.le_stlinkFilePath)
        self.__writeCfgSTLinkBurnPath(ui.le_stlinkBurnFilePath)
        self.__writeCfgSTLinkChipType(ui.cmb_stlinkChipType)
        self.__writeCfgSTLinkBurnAddr(ui.le_stlinkBurnAddr)
        with open("config.ini", "w+", encoding="utf-8-sig") as f:
            self.cf.write(f)
